#include "threadtasks.h"
#include "../tcp/basetcp.h"
#include "config/constants.h"

#include <QEventLoop>

ThreadTasks::ThreadTasks(QObject *parent)
{
    isNotify = 0;
//    realDataModel.controlStatusVec.resize(10);
//    realDataModel.analogVec.resize(10);
    //connect(this, SIGNAL(emitHandle(QByteArray)), this, SLOT(onHandle(QByteArray)));
    moveToThread(this); //必须添加，实现子线程之间通讯
}

void ThreadTasks::onReceiveFromTcp(QByteArray ba)
{
    /// 和 run是同一个线程。
    ///
    ///
    if(ba.size() < 3)
    {
        return;
    }
    QString rawCommand = parseCommand(ba);
    std::string tempStr = rawCommand.toStdString();
    std::string keyCommand = tempStr.substr(0, 3);
    if(keyCommand == ":DC")
    {
        tempStr = tempStr.substr(3, tempStr.size()-4);
        rawCommand = QString(tempStr.c_str());
        float disp = rawCommand.toFloat();

        realDataModel.analogVec[0] = disp;

        LOG_INFO << "disp = " << disp;
    }

    realDataModel.controlStatusVec.resize(1);
    realDataModel.controlStatusVec[0] = ba.at(0);
//    emit emitHandle(rawData);
    emit notifyMainWindowSignal(realDataModel);
}

void ThreadTasks::onHandle(QByteArray ba)
{
//    QMutexLocker lock(&mutex);
//    sleep(5);
    rawData = ba;


    qDebug() << "数据处理线程 thread id = " << QThread::currentThread();
}

void ThreadTasks::run()
{
//    QEventLoop eventLoop(this);
//    eventLoop.processEvents();

    this->exec();
}

QString ThreadTasks::parseCommand(const QByteArray &rawData)
{
    QString cmd = rawData;
    return cmd;
}
